package com.example.loganalysis.controller;

import com.example.loganalysis.dao.TLoginLogDao;
import com.example.loganalysis.entity.TLoginLog;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/logs")
public class LoginLogController {

    private static final Logger logger = LoggerFactory.getLogger(LoginLogController.class);

    private final TLoginLogDao tLoginLogDao;

    @Autowired
    public LoginLogController(TLoginLogDao tLoginLogDao) {
        this.tLoginLogDao = tLoginLogDao;
    }

    @PostMapping("/insertlogin")
    public String insertLog(@RequestBody TLoginLog tLoginLog) {
        logger.info("Received log: {}", tLoginLog);
        try {
            // 插入数据库
            tLoginLogDao.insertLoginLogs(tLoginLog);
            logger.info("Log inserted successfully: {}", tLoginLog);
            return "Log inserted successfully.";
        } catch (Exception e) {
            logger.error("Error inserting log: {}", tLoginLog, e);
            return "Error inserting log.";
        }
    }

    @GetMapping("/login_ipfs_hash")
    public ResponseEntity<String> getLoginIpfsHash(@RequestParam String log_id) {
        String ipfsHash = tLoginLogDao.getIpfsHashByLogId(log_id);
        if (ipfsHash == null) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Login IPFS Hash not found for log_id: " + log_id);
        }
        return ResponseEntity.ok(ipfsHash);
    }
}
